package me.shingohu.man.base;

import android.app.Application;

import java.util.List;

import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.di.component.DaggerAppComponent;
import me.shingohu.man.di.module.AppModule;
import me.shingohu.man.di.module.ClientModule;
import me.shingohu.man.di.module.EventBusModule;
import me.shingohu.man.di.module.GlobeConfigModule;
import me.shingohu.man.di.module.ImageModule;
import me.shingohu.man.intergation.ConfigModule;
import me.shingohu.man.intergation.InitUtilManager;
import me.shingohu.man.intergation.ManifestParser;

/**
 * Created by hujie on 17/4/14.
 */

public class BaseApplication extends Application {

    private static BaseApplication mApplication;
    private AppComponent mAppComponent;


    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        initUtils();
        initComponent();
        
    }

    private void initUtils() {
        InitUtilManager.init(this);
    }

    private void initComponent() {

        List<ConfigModule> modules = new ManifestParser(this).parse();

        mAppComponent = DaggerAppComponent
                .builder()
                .appModule(new AppModule(this))
                .clientModule(new ClientModule())
                .eventBusModule(new EventBusModule())
                .imageModule(new ImageModule())
                .globeConfigModule(getGlobeConfigModule(this, modules))
                .build();
        for (ConfigModule module : modules) {
            module.registerComponents(this, mAppComponent.repositoryManager());
        }

    }

    /**
     * 将app的全局配置信息封装进module(使用Dagger注入到需要配置信息的地方)
     * 需要在AndroidManifest中声明{@link ConfigModule}的实现类,和Glide的配置方式相似
     *
     * @return
     */
    private GlobeConfigModule getGlobeConfigModule(Application context, List<ConfigModule> modules) {

        GlobeConfigModule.Builder builder = GlobeConfigModule
                .builder()
                .baseurl("https://api.github.com");//为了防止用户没有通过GlobeConfigModule配置baseurl,而导致报错,所以提前配置个默认baseurl

        for (ConfigModule module : modules) {
            module.applyOptions(context, builder);
        }
        return builder.build();
    }


    /**
     * 将AppComponent返回出去,供其它地方使用, AppComponent接口中声明的方法返回的实例,在getAppComponent()拿到对象后都可以直接使用
     *
     * @return
     */
    public AppComponent getAppComponent() {
        return mAppComponent;
    }


    public static BaseApplication getInstance() {
        return mApplication;
    }


}
